package com.fred.websocket.ws;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 推送WebSocket
 * @Author fred
 */
@Slf4j
@Component
@ServerEndpoint("/websocket/{pid}")
public class WebScoketServer {

    /**
     * 静态变量，用来记录当前在线连接数
     */
    private static int onlineCount = 0;

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static CopyOnWriteArraySet<WebScoketServer> webSocketSet = new CopyOnWriteArraySet<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    /*接收id*/
    private String pid = "";


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("pid") String pid) {
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();
        this.pid = pid;


        log.info("新客户端接入,sid:【{}】, 当前接入数:【{}】", pid, getOnlineCount());
    }


    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        subOnlineCount();
        log.info("【{}】连接关闭！当前在线人数为: {}", this.pid, getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到客户端消息:{}", message);
        try {
            //群发消息
            for (WebScoketServer item : webSocketSet) {
                item.sendMessage(message);
            }

        } catch (IOException e) {
            log.error("推送异常, 内容:{}", message, e);
        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误", error);
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message, @PathParam("pid") String pid) throws IOException {
        try {
            if (StringUtils.isBlank(message)) {
                return;
            }
            for (WebScoketServer item : webSocketSet) {
                /*这里可以做逻辑判断，只推送给当前pid，为空则全部推送*/
                if (StringUtils.isBlank(pid)) {
                    item.sendMessage(message);
                } else if (item.pid.equals(pid)) {
                    item.sendMessage(message);
                }
            }

        } catch (IOException e) {
            log.error("推送异常, 内容:{}", message, e);
        }
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    private static synchronized void addOnlineCount() {
        WebScoketServer.onlineCount++;
    }

    private static synchronized void subOnlineCount() {
        WebScoketServer.onlineCount--;
    }
}
